package com.thb.utils;

import java.text.SimpleDateFormat;

import com.alibaba.fastjson.JSONObject;

public class JSONUtil {
	private static JSONObjectMapper mapper;
	
//	private static final Logger log = LoggerFactory.getLogger(JSONUtil.class);

	/**
	 * 获取ObjectMapper实例
	 * 
	 * @param createNew
	 *            方式：true，新实例；false,存在的mapper实例
	 * @return
	 */
	public static synchronized JSONObjectMapper getMapperInstance(boolean createNew) {
		if (createNew) {
			mapper = new JSONObjectMapper();
			mapper.setDateFormat(new SimpleDateFormat(DateUtils.LONG_SIMPLE_DATE));
			return mapper;
		} else if (mapper == null) {
			mapper = new JSONObjectMapper();
			mapper.setDateFormat(new SimpleDateFormat(DateUtils.LONG_SIMPLE_DATE));
			return mapper;
		}
		return mapper;
	}

	/**
	 * 将java对象转换成json字符
	 * 
	 * @param obj
	 *            准备转换的对
	 * @return json字符
	 * @throws Exception
	 */
	public static String beanToJson(Object obj) {
		try {
			JSONObjectMapper objectMapper = getMapperInstance(false);
			String json = objectMapper.writeValueAsString(obj);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}
	
	public static String beanToJSON(Object javaObj){
        
        String json;
        json = JSONObject.toJSONString(javaObj);
        return json.toString();
        
    }

	/**
	 * 将java对象转换成json字符
	 * 
	 * @param obj
	 *            准备转换的对
	 * @param createNew
	 *            ObjectMapper实例方式:true，新实例;false,存在的mapper实例
	 * @return json字符
	 * @throws Exception
	 */
	public static String beanToJson(Object obj, Boolean createNew)
			throws Exception {
		try {
			JSONObjectMapper objectMapper = getMapperInstance(createNew);
			String json = objectMapper.writeValueAsString(obj);
			return json;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 将json字符串转换成java对象
	 * 
	 * @param <T>
	 * 
	 * @param json
	 *            准备转换的json字符
	 * @param cls
	 *            准备转换的类
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static <T> T jsonToBean(String json, Class<?> cls)
			throws Exception {
		try {
			JSONObjectMapper objectMapper = getMapperInstance(false);
			Object obj = objectMapper.readValue(json, cls);
			return (T) obj;
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 将json字符串转换成java对象
	 * 
	 * @param json
	 *            准备转换的json字符
	 * @param cls
	 *            准备转换的类
	 * @param createNew
	 *            ObjectMapper实例方式:true，新实例;false,存在的mapper实例
	 * @return
	 * @throws Exception
	 */
	public static Object jsonToBean(String json, Class<?> cls, Boolean createNew)
			throws Exception {
		try {
			JSONObjectMapper objectMapper = getMapperInstance(createNew);
			Object vo = objectMapper.readValue(json, cls);
			return vo;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

}